package com.ark.frigate.dingtalk.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.RuntimeJsonMappingException;
import com.fasterxml.jackson.databind.SerializationFeature;

/**
 * Json 转化工具
 *
 * @author Along(ZengWeiLong)
 * @ClassName: MessageJson
 * @date 2016年9月8日 下午2:26:53
 */
public class DingTalkMessageJson {

    private static ObjectMapper objectMapper;

    static {
        objectMapper = new ObjectMapper();
        // json --> pojo
        // 1.设置输入时忽略在JSON字符串中存在，但Java对象实际没有的属性
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 2.设置禁止将空对象转化到
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        // 3.按字母顺序排序属性
        // 包含所有属性
        objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
        // 默认转化时间格式
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        // 有属性不能映射的时候不报错
        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        // 不序列化为NULL值的Map
        objectMapper.disable(SerializationFeature.WRITE_NULL_MAP_VALUES);
    }

    public static String toJson(Object obj) {

        try {
            return objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            throw new RuntimeJsonMappingException("解析对象错误: " + obj + " object to jsonString");
        }
    }
}
